package com.ruikong.dazhi.service.impl.baseinfo;

import com.ruikong.dazhi.dao.basicinfo.StockMapper;
import com.ruikong.dazhi.entity.basicinfo.StockType;
import com.ruikong.dazhi.dao.basicinfo.StockTypeMapper;
import com.ruikong.dazhi.model.output.TreeMenuOutput;
import com.ruikong.dazhi.service.basicinfo.IStockTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * (StockType)表服务实现类
 *
 * @author HuaJiaYi
 * @since 2021-09-09 13:22:10
 */
@Service("stockTypeService")
public class StockTypeServiceImpl implements IStockTypeService {
    @Autowired
    private StockTypeMapper stockTypeMapper;
    @Autowired
    private StockMapper stockMapper;

    @Override
    public StockType queryById(Integer id) {
        return stockTypeMapper.queryById(id);
    }

    @Override
    public List<StockType> queryByPid(int id) {
        return stockTypeMapper.queryByPId(id);
    }

    @Override
    public int insert(StockType p) {
        if (stockTypeMapper.getId() == null) {
            p.setStockTypeId(1);
        } else {
            p.setStockTypeId(stockTypeMapper.getId() + 1);
        }
        return stockTypeMapper.insert(p);
    }

    @Override
    public int update(StockType p) {
        return stockTypeMapper.update(p);
    }

    @Override
    public String deleteById(Integer id) {
        //这个类下面是否有子类
        List<StockType> list = queryByPid(id);
        if (list.size() > 0) {
            return "要删除的原料类别存在子类别，不允许被删除";
        }
        int iCount = stockMapper.queryByTypeId(id);
        if (iCount > 0) {
            return "要删除的原料类别存在原料，不允许被删除";
        }
        if (stockTypeMapper.deleteById(id) > 0) {
            return "";
        } else {
            return "删除失败";
        }
    }

    public void addTree(List<TreeMenuOutput> tree, int pid) {
        List<StockType> StockType_list = stockTypeMapper.queryByPId(pid);
        for (StockType root : StockType_list) {
            TreeMenuOutput menu = new TreeMenuOutput();
            menu.setId(root.getStockTypeId());
            menu.setName(root.getStockTypeName());
            menu.setpId(pid);
            tree.add(menu);
            addTree(tree, menu.getId());
        }
    }

    @Override
    public List<TreeMenuOutput> getStockTypeTree() {
        List<TreeMenuOutput> tree_list = new ArrayList<>();
        TreeMenuOutput root = new TreeMenuOutput();
        root.setpId(-1);
        root.setId(0);
        root.setName("原料类别");
        tree_list.add(root);
        this.addTree(tree_list, 0);
        return tree_list;
    }


    @Override
    public Integer isExist(StockType s) {
        return this.stockTypeMapper.isExist(s);
    }
}
